<?php
/*
 * 车款类
 * @package    auto
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 9f9efbb5b15574cccc561d7cd92071ad1ac09eb4 $
 */

/**
 * 车款信息更新类
 * Class AutoModelModule
 */
class AutoModelModule extends BasicModule {

	/** @var  车款ID */
	private $_amid;

	/** @var  车款信息存储 */
	private $_am;

	/** @var string 主表名称 */
	private $_table;

	/** @var array 主表字段 */
	private $_fields;

	/** @var  扩展表 */
	private $_tabExt;

	/** @var  扩展表字段 */
	private $_fieldsExt;

	/** @var  图片存储表 */
	private $_picTable;

	/** @var  车款类型 */
	private $_modelType;

	/** @var int|string 模块ID */
	private $_moduleid;

	/** @var array 属性分组的对应关系 */
	private $_propGroupCorr = array(
		'passenger'  => 3691,
		'commercial' => 3690,
		'rv'         => 3692
	);

	/** @var  属性分组 */
	private $_propGroup;

	/**
	 * 根据类型构造函数
	 * @param $type
	 */
	public function __construct($type) {
		global $moduleid;
		parent::__construct();
		$this->_tabExt = AutoModel::getTableExt($type);
		if (!$this->_tabExt) {
			return $this->err('不存在的表名称!');
		}
		$this->_modelType = $type;
		$this->_table     = Table::name(Table::NAME_AUTO_MODEL);
		$this->_fields    = array(
			'arbid',
			'armid',
			'arcid',
			'acid',
			'name',
			'price',
			'linkurl',
			'enginetype',
			'model_thumb',
			'emission',
			'gearbox',
			'year',
			'country',
			'addtime',
			'edittime',
			'username',
			'issale',
			'isdisplay',
			'modeltype',
			'status',
		);
		$this->_initPropGroup();
		$this->_fieldsExt = PCache::read('fields-' . str_replace($this->_db->getPre(), '', $this->_tabExt) . '.php');
		$this->_initExtFields();
		$this->_moduleid = $moduleid;
	}

	/**
	 * 获取主表
	 * @return string
	 */
	public function getMainTable() {
		return $this->_table;
	}

	/**
	 * 获取处理的属性表
	 * @return mixed
	 */
	public function getPropTable() {
		return $this->_tabExt;
	}

	/**
	 * 车款表主字段
	 * @return array|mixed|string
	 */
	public function getMainFields() {
		return PCache::read('fields-' . str_replace($this->_db->getPre(), '', $this->_table) . '.php');
	}

	/**
	 * 获取属性组
	 * @return mixed
	 */
	public function getPropGroup() {
		return $this->_propGroup;
	}

	/**
	 * 设置车款ID
	 * @param $amid
	 */
	public function setAmid($amid) {
		$this->_amid = $amid;
	}

	/**
	 * 完善需要的资料
	 */
	public function set($post) {
		global $_username, $DT_TIME;
		$new              = array();
		$new['arbid']     = Filter::vint($post['arbid']);
		$new['arcid']     = Filter::vint($post['arcid']);
		$new['armid']     = AutoRank::getArmidByArcid($new['arcid']);
		$new['name']      = Filter::vtitle($post['name']);
		$new['username']  = $_username;
		$new['listorder'] = 0;
		$new['modeltype'] = $this->_modelType;
		$new['edittime']  = $DT_TIME;
		return $new;
	}
	/**

	 * 锁定图片存储表
	 * @param $arcid 车系id
	 */
	public function setPicTable($carId) {
		$this->_picTable =  Table::autoPicture($carId);
	}
	/**
	 * 检测必填项是否都填充了
	 */
	public function pass($post) {
		if (!$post['arbid']) return $this->err('请选择品牌');
		if (!$post['arcid']) return $this->err('请选择车系');
		if (!$post['name']) return $this->err('请填写车款名称');
		return true;
	}

	/**
	 * 编辑
	 * @param $post
	 * @param $model
	 */
	public function edit($post, $model) {
		$post = $this->set($post);
		$r    = $this->getOne($this->_amid);
		if ($model['model_thumb'] == '') {
			if ($r['model_thumb']) {
				Picture::deleteAll($r['model_thumb']);
			}
		} else {
			if ($r['model_thumb'] !== $model['model_thumb']) {
				Picture::deleteAll($r['model_thumb']);
				Session::del($this->_moduleid . '_model_thumb');
			}
		}
		$this->_updatePicture($post, $r);
		$this->_updateModel($this->_amid, $post);
		$this->_updateModel($this->_amid, $model);
		$this->_updateModelExt($this->_amid, $model);
	}

	/**
	 * 更新图片库
	 * @param $post
	 * @param $r
	 */
	public function _updatePicture($post,$r){
		if($post['arbid']!=$r['arbid'] || $post['arcid']!=$r['arcid']){
			$newTable = Table::autoPicture($post['arcid']);
			$oldTable = Table::autoPicture($r['arcid']);
			$sql ="INSERT INTO {$newTable}(arbid,armid,arcid,amid,alid,title,imgurl,description,status,level,listorder,editor,addtime,edittime)SELECT arbid,armid,arcid,amid,alid,title,imgurl,description,status,level,listorder,editor,addtime,edittime FROM {$oldTable} where amid={$this->_amid}";
;           if($this->_db->query($sql)){
				$sql = Sql::update($newTable,array('arbid'=>$post['arbid'],'arcid'=>$post['arcid']),'amid='.$this->_amid);
				if($this->_db->query($sql)){
					$sql = Sql::delete($oldTable,'amid='.$this->_amid);
					$this->_db->query($sql);
				};
			};
		}
	}
	/**
	 * 添加资料
	 * @param $post
	 * @param $model
	 */
	public function add($post, $model) {
		global $DT_TIME, $_userid;
		$post            = $this->set($post);
		$post['addtime'] = $DT_TIME;
		ThumbUpload::clearPicture($this->_moduleid.'_model_thumb', $post['model_thumb'], '', $_userid);
		if ($this->_db->query(Sql::insert($this->_table, $post))) {
			$this->_amid      = $this->_db->insertId();
			$model['linkurl'] = url('auto/model', 'modelid='.$this->_amid);
			$this->_updateModel($this->_amid, $model);
			$this->_addModelExt($this->_amid, $model);
		}
	}

	/**
	 * 删除车款
	 * @param $amid
	 */
	public function clear($amid) {
		if (is_array($amid)) {
			foreach ($amid as $mid) {
				$this->clear($mid);
			}
		} else {
			$am = $this->getOne($amid);
			if ($am['model_thumb']) {
				Picture::deleteAll($am['model_thumb']);
			}
			$this->_db->query(Sql::delete($this->_table, 'amid=' . $amid));
			$this->_db->query(Sql::delete($this->_tabExt, 'amid=' . $amid));
		}
	}


	/**
	 * 更新车型的名称
	 * @param $id
	 * @param $model
	 * @return array|bool|mixed|mysqli_result|string
	 */
	public function updateModelName($id, $model) {
		$sql = Sql::update($this->_table, "name='$model'", "amid=$id");
		return $sql? $this->_db->query($sql) : false;
	}

	/**
	 * 更新车款价格
	 * @param $id
	 * @param $price
	 * @return array|bool|mixed|mysqli_result|string
	 */
	public function updateModelPrice($id, $price) {
		$sql = Sql::update($this->_table, "price='$price'", "amid=$id");
		return $sql? $this->_db->query($sql) : false;
	}

	/**
	 * 更新车款的分类
	 * @param $items
	 * @param $arbid
	 * @param $armid
	 * @param $arcid
	 */
	public function updateCategory($items, $arbid, $armid, $arcid) {
		$update = array(
			'arbid' => $arbid,
			'armid' => $armid,
			'arcid' => $arcid,
		);
		$sql    = Sql::update($this->_table, $update, "amid in(" . implode(',', $items) . ")");
		$this->_db->query($sql);
	}

	/**
	 * 删除一条车款
	 * @param $amid
	 */
	public function delete($amid) {
		if (is_array($amid)) {
			foreach ($amid as $mid) {
				$this->delete($mid);
			}
		} else {
			$del=$this->_db->getOne("SELECT * FROM {$this->_table} WHERE amid={$amid}");
			if($del['status']==0){
				$this->_db->query(Sql::delete($this->_table, 'amid=' . $amid));
				$this->_db->query(Sql::delete($this->_tabExt, 'amid=' . $amid));
				$this->setPicTable($del['arcid']);
				$delPic = $this->_db->getAll("SELECT * FROM {$this->_picTable} WHERE amid={$amid}");
				foreach($delPic as $picValue){
					Picture::deleteAll($picValue['imgurl']);
					$this->_db->query(Sql::delete($this->_picTable, "apid={$picValue['apid']}"));
				}
			}else{
				$this->_db->query(Sql::update($this->_table, 'status=0', 'amid=' . $amid));
			}
		}
	}

	/**
	 * 禁用车款, 不在前台显示
	 * @param $amid
	 */
	public function disable($amid) {

	}

	/**
	 * 获取一条车款的详细信息
	 * @return array|null
	 */
	public function getOne() {
		$info      = $this->_db->getOne("select * from {$this->_table} m, {$this->_tabExt} e where m.amid=e.amid and m.amid = {$this->_amid}");
		$this->_am = $info;
		return $this->_am;
	}

	/**
	 * 获取车款的列表信息
	 */
	public function getList($condition = '', $order = 'listorder ASC,amid ASC') {
		$num = $this->_db->count($this->_table, $condition);
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$lists = $this->_db->getAll($sql);
		return $lists;
	}

	/**
	 * 初始化参数组
	 */
	private function _initPropGroup() {
		$props         = PCache::read('autoCategory-param_group.php');
		$propsChildids = explode(',', $props[$this->_propGroupCorr[$this->_modelType]]['arrchildid']);
		array_shift($propsChildids);
		$this->_propGroup = array();
		foreach ($props as $k => $v) {
			if (in_array($k, $propsChildids)) {
				$this->_propGroup[$k] = $v;
			}
		}
		$this->_propGroup[99999] = array(
			'field' => array(),
			'name'  => '未分类',
			'arid'  => 99999
		);
	}

	/**
	 * 初始化扩展字段
	 */
	private function _initExtFields() {
		foreach ($this->_fieldsExt as $k => $field) {
			if (!empty($field['param_group'])) {
				$fpg = $field['param_group'];
				if (!isset($this->_propGroup[$fpg]['field'])) {
					$this->_propGroup[$fpg]['field']     = array();
					$this->_propGroup[$fpg]['field'][$k] = $field;
				} else {
					$this->_propGroup[$fpg]['field'][$k] = $field;
				}
			} else {
				$this->_propGroup[99999]['field'][$k] = $field;
			}
		}
	}


	/**
	 * 更新车款数据
	 * @param $id
	 * @param $model
	 */
	private function _updateModel($id, $model) {
		$sql = Sql::update($this->_table, $model, 'amid=' . $id, array(), $this->_fields);
		if ($sql) {
			$this->_db->query($sql);
		}
	}

	/**
	 * 获取字段的名称
	 * @param $fields
	 * @return array
	 */
	private function _getFieldsName($fields) {
		$arr = array();
		foreach ($fields as $v) {
			$arr[] = $v['name'];
		}
		return $arr;
	}

	/**
	 * 添加车型扩展
	 * @param $id
	 * @param $model
	 */
	private function _addModelExt($id, $model) {
		$model['amid'] = $id;
		$fields        = $this->_getFieldsName($this->_fieldsExt);
		$fields[]      = 'amid';
		$this->_db->query(Sql::insert($this->_tabExt, $model, $fields));
	}

	/**
	 * 更新车型扩展
	 * @param $id
	 * @param $model
	 */
	private function _updateModelExt($id, $model) {
		$fields = $this->_getFieldsName($this->_fieldsExt);
		$sql    = Sql::update($this->_tabExt, $model, 'amid=' . $id, $this->_am, $fields);
		if ($sql) {
			$this->_db->query($sql);
		}
	}
}